

package com.fg.object.oauth2;

import com.fg.common.entity.Dto.UserDto;
import com.fg.common.enums.ResponseEnum;
import com.fg.common.util.Assert;
import com.fg.room.service.UserService;
import lombok.AllArgsConstructor;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 认证
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
@AllArgsConstructor
public class OAuth2Realm extends AuthorizingRealm {

    /**
     * 延迟加载  避免shiro在spring之前初始化bean  导致spring部分功能失效
     */
    @Lazy
    private final UserService sysUserService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof BearerToken;
    }


    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Object primaryPrincipal = principals.getPrimaryPrincipal();
        Assert.assertNotNull(primaryPrincipal, ResponseEnum.TOKEN_INVALID);
        UserDto user = (UserDto) primaryPrincipal;
        Set<String>  permsSet = user.getPerms();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        info.setRoles(user.getRoleNameList());
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        BearerToken bearerToken = (BearerToken) token;
        UserDto user = sysUserService.getUserByToken(bearerToken.getToken());
        Assert.assertNotNull(user, ResponseEnum.TOKEN_INVALID);
        return new SimpleAuthenticationInfo(user, bearerToken.getToken(), getName());
    }
}
